<template>
  <el-dialog :visible.sync="dialogTableVisible" :append-to-body="true" :lock-scroll="false" :title="isEdit?'Edit':'Create'" @close="handleCloseDetailDialog" width="800px">
    <el-form ref="postForm" :model="postForm" :rules="rules" label-position="left" label-width="100px" style="margin-left:50px;">
      <el-form-item :label="$t('rolefiles.name')" prop="name" >
        <el-col :span="20">
          <el-input v-model="postForm.name" :label="$t('rolefiles.name')"/>
        </el-col>
      </el-form-item>

      <el-form-item :label="$t('rolefiles.isadmin')" prop="isadmin">
        <el-radio-group v-model="postForm.isadmin">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item :label="$t('table.area')">
            <el-select
              v-model="postForm.area_id"
              style="width: 560px;"
              multiple
              filterable
              allow-create
              default-first-option
               @change="handleLocationChange"
              :placeholder="$t('placeholder.select')">
              <el-option
                v-for="item in areaOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item :label="$t('table.location')">
            <el-select
              v-model="postForm.location_id"
              style="width: 450px;"
              multiple
              filterable
              allow-create
              default-first-option
              :placeholder="$t('placeholder.select')" >
              <el-option-group
                v-for="area in locationOptions"
                :key="area.id"
                :label="area.name"
                :value="area.id">
                <el-option
                  v-for="location in area.locations"
                  :key="location.id"
                  :label="location.name"
                  :value="location.id">
                </el-option>
              </el-option-group>
            </el-select>
            <el-checkbox v-model="is_location_all" @change="handleLocationAll">{{ $t('table_element.available.all') }}</el-checkbox>
          </el-form-item>

      <el-form-item :label="$t('rolefiles.permission')" prop="permission" >
        <el-col :span="20">
          <el-tree
            :data="permissionList"
            show-checkbox
            node-key="id"
            ref="tree"
            default-expand-all
            :default-checked-keys="postForm.permissions"
            :expand-on-click-node="false"
            :props="permissionProps">
          </el-tree>
          <!-- <el-checkbox-group v-model="postForm.permissions" :checked="postForm.permissions">
            <tree ref="tree" :depth="0" :permission-list="permissionList" />
          </el-checkbox-group> -->
        </el-col>
      </el-form-item>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCloseDetailDialog">{{ $t('table.cancel') }}</el-button>
      <el-button type="primary" @click="submitForm('postForm')">{{ $t('table.submit') }}</el-button>
    </div>

  </el-dialog>
</template>
<script>

import areaApi from '@/api/area/area'
import roleApi from '@/api/system/role'
import ScrollPane from '../../../../../components/ScrollPane/index'
import { fetchAll as fetchLocation, fetchGroup as fetchLocationGroup } from '@/api/location'

const defaultForm = {
  name: '',
  isadmin: 0,
  area_id: [],
  location_id: [],
  permissions: []
}

export default {
  name: 'Detail',
  components: { ScrollPane },
  data() {
    return {
      postForm: Object.assign({}, defaultForm),
      rules: {
        name: [
          { required: true, message: 'name is required', trigger: 'blur' }
        ],
        email: [
          { required: true, message: 'email is required', trigger: 'blur' }
        ],
        password: [
          { required: true, message: 'password is required', trigger: 'blur' }
        ]
      },
      isEdit: false,
      // areaList: this.$store.getters.stat,
      imageUrl: '',
      recordid: 0,
      is_location_all: false,
      dialogTableVisible: false,
      permissionList: [],
      locationOptions: [],
      permissionProps: {
        children: '_child',
        label: 'name',
        id: 'id'
      }
    }
  },
  computed: {
    lang() {
      return this.$store.getters.language
    },
    areaOptions: function () {
        return this.$store.state.locale.allareas
    }
  },
  created() {
    // this.handleAreaRecord()
    if (this.isEdit) {
      const id = this.editId || (this.$route.params && this.$route.params.id)
      this.showRecord(id)
    } else {
      this.postForm = Object.assign({}, defaultForm)
    }
  },

  mounted() {

  },

  methods: {
    showRecord(id) {
      roleApi.showRecord(id).then(response => {
        const serviceResponse = response.data
        if (serviceResponse.code === 0) {
          this.permissionList = serviceResponse.data.permissionList
          this.postForm = Object.assign({}, this.postForm, serviceResponse.data.record)
          this.postForm.permissions = serviceResponse.data.selectPermission
          this.postForm.area_id = serviceResponse.data.area_id
          this.postForm.location_id = serviceResponse.data.location_id
          this.getLocation()
        }
      }).catch(err => {
        console.log(err)
      })
    },

    handleCreateRecord() {
      roleApi.createRecord().then(response => {
        const serviceResponse = response.data
        if (serviceResponse.code === 0) {
          this.permissionList = serviceResponse.data.permissionList
        }
      }).catch(err => {
        console.log(err)
      })
    },

    submitForm(formName) {
      this.postForm.permissions = this.$refs.tree.getCheckedKeys() // 获取tree值
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // this.postForm.permissions = Array.from(new Set(checkedKey))

          if (this.editId > 0) {
            roleApi.updateRecord(this.editId, this.postForm).then(response => {
              const serviceResponse = response.data
              if (serviceResponse.code === 0) {
                this.$message({
                  type: 'success',
                  message: serviceResponse.msg
                })
                this.handleCloseDetailDialog()
              } else {
                this.$message({
                  type: 'error',
                  message: serviceResponse.msg
                })
              }
            })
          } else {
            roleApi.storeRecord(this.postForm).then(response => {
              const serviceResponse = response.data
              if (serviceResponse.code === 0) {
                this.$message({
                  type: 'success',
                  message: serviceResponse.msg
                })
                this.handleCloseDetailDialog()
              } else {
                this.$message({
                  type: 'error',
                  message: serviceResponse.msg
                })
              }
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(postForm) {
      this.$refs[postForm].resetFields()
    },

    handShowDetailDialog(id) {
      if (id > 0) {
        this.isEdit = true
        this.editId = id
        this.showRecord(id)
      } else {
        this.isEdit = false
        this.handleCreateRecord()
        this.postForm = Object.assign({}, defaultForm)
      }

      this.dialogTableVisible = true
    },
    handleCloseDetailDialog() {
      this.resetForm('postForm')
      this.editId = 0
      this.$emit('indexRecord')
      this.dialogTableVisible = false
    },
    handleLocationChange() {
      this.getLocation();
    },
    getLocation() {// 地址列表
      let params = {
        area: this.postForm.area_id
      }
      fetchLocationGroup(params).then((res) => {
        this.locationOptions = res.data.data
      })
    },
    handleLocationAll() {
      let area, location;
      this.postForm.location_id = [];
      if (this.is_location_all) {
        for(area in this.locationOptions) {
          for(location in this.locationOptions[area].locations) {
            this.postForm.location_id.push(this.locationOptions[area].locations[location].id);
          }
        }
      }
    },
    // handleAreaRecord() {
    //   areaApi.areaList({'isAll':1}).then(response => {
    //     const res = response.data
    //     if (res.code === 0) {
    //       this.areaList = res.data
    //     }
    //   }).catch(err => {
    //     console.log(err)
    //   })
    // }
  }

}
</script>

<style>
  .el-tree-node{
    float: left;
  }
</style>
